package com.btpj.jwt.service;

import com.btpj.jwt.entity.RoleUser;
import com.btpj.jwt.entity.User;
import com.btpj.jwt.mapper.RoleMapper;
import com.btpj.jwt.mapper.RoleUserMapper;
import com.btpj.jwt.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserService implements UserDetailsService {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    UserMapper userMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    RoleMapper roleMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    RoleUserMapper roleUserMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userMapper.selectUserByName(s);
        if (user == null) {
            user = new User();
        }
        user.setRoles(roleMapper.getRolesByUserId(user.getId()));
        return user;
    }

    /**
     * 注册
     *
     * @param user user
     * @return 是否成功
     */
    public boolean register(User user) {
        userMapper.insertSelective(user);
        RoleUser roleUser = new RoleUser();
        roleUser.setRoleId(2);
        roleUser.setUserId(userMapper.selectUserByName(user.getUsername()).getId());
        return roleUserMapper.insert(roleUser) == 1;
    }
}
